package GUI.TabPanel;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.*;

import Logic.TaskMaintain;
import Struct.Tables;

public class DataBasePanel extends JScrollPane {

	private ArrayList<String> src;
	private ArrayList<Tables> table;
	private ArrayList<JCheckBox> checkboxs;
	private JButton save = new JButton("Save");
	private JPanel panel = new JPanel();
	private BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
	private String tablename;
	private String Mac_ID;
	private JLabel Unique_ID = new JLabel("Unique_ID:");
	private JTextField Unique_IDText = new JTextField(1);
	
	public void setMac_ID(String Mac_ID) {
		this.Mac_ID = Mac_ID;
	}
	
	public DataBasePanel() {
		this.setViewportView(panel);
		save.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(!Unique_IDText.getText().isEmpty()) {
					ArrayList<String> tmp = new ArrayList<String>();
					for(JCheckBox tmps : checkboxs) {
						if(tmps.isSelected()) {
							//System.out.println(tmps.getText());
							tmp.add(tmps.getText());
						}
					}
					if(tmp.size() != 0)
						try {
							TaskMaintain.generateTask(tmp, tablename, Mac_ID, Unique_IDText.getText());
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					System.out.println(tablename + Mac_ID + Unique_IDText.getText());
					
						//ComWork.generateTask(tmp, tablename, Mac_ID, Unique_IDText.getText());
					//System.out.println("-------------------------------------");
				} else {
					JOptionPane.showMessageDialog(null, "Please complete Unique_ID");
				}
			}
			
		});
	}
	
	/** 2014.11.27   迭代表命名冲突修正 */
	public void Refresh(Object SelectObject) {
		panel.removeAll();
		panel.setLayout(layout);
		checkboxs = new ArrayList<JCheckBox>();
		
		if(SelectObject != null) {
			tablename = (String) SelectObject;
			for(Tables table : this.table) {
				if(table.name == tablename) {
					src = table.getColumns();
					break;
				}
			}
			//panel.add(Box.createVerticalGlue());
			panel.add(Box.createVerticalStrut(20));
			//System.out.println(src.size());
			for(int i=0; i<src.size(); ++i) {
				JCheckBox tmps = new JCheckBox(src.get(i));
				checkboxs.add(tmps);
				panel.add(Box.createVerticalStrut(10));
				panel.add(tmps);
			}
			//panel.add(Box.createVerticalGlue());
			panel.add(Box.createVerticalStrut(80));
			panel.add(Unique_ID);
			//Unique_IDText.setBounds(0, 10, 10, 10);
			panel.add(Unique_IDText);
			panel.add(Box.createVerticalStrut(20));
			panel.add(save);
			panel.add(Box.createVerticalStrut(20));
			//save.removeAll();
			panel.updateUI();
			panel.revalidate();
		}
	}
	
	public void setSrc(ArrayList<Tables> table) {
		this.table = table;
	}
}
